using Box;
using Godot;
using System;

public partial class ProjectMenu : MenuButton
{
	const long CREATE_ID = 0;
	const long OPEN_ID = 1;
	const long SAVE_ID = 2;
	const long SAVE_AS_ID = 3;

	public TreeTabContainer TreeTabContainer;

	public ProjectCreateWindow ProjectCreateWindow;
	public ProjectOpenWindow ProjectOpenWindow;

	public override void _Ready()
	{
		ProjectCreateWindow = GetNode<ProjectCreateWindow>("ProjectCreateWindow");
		ProjectOpenWindow = GetNode<ProjectOpenWindow>("ProjectOpenWindow");

		var popup_menu = GetPopup();
		popup_menu.IdPressed += _onPressedItem;
	}

	public void _onPressedItem(long id) {
		switch (id) {
			case CREATE_ID 	:{
				ProjectCreateWindow.Show();
			};break;
			case OPEN_ID 	: {
				ProjectOpenWindow.Show();
			}break;
			case SAVE_ID: {
				onSave();
			}break;
			case SAVE_AS_ID: {
				
			}break;
		}
	}

    public override void _ExitTree()
    {
		//自动保存
        onSave();
    }

    public void onSave() {
		//清理已经删除的Tree
		DirAccess trees_dir = DirAccess.Open($"{ProcessTreeEditor.ProjectPath}/trees");
		trees_dir.ListDirBegin();
		string next = trees_dir.GetNext();
		while(next != "") {
			if(!trees_dir.CurrentIsDir()) {
				if(TreeTabContainer.GetNodeOrNull(next) == null) {
					trees_dir.Remove(next);
				}
			}

			next = trees_dir.GetNext();
		}

		foreach(Node item in TreeTabContainer.GetChildren()) {
			if(item is ProcessTreeGraphEditor) {
				ProcessTreeGraphEditor edit = item as ProcessTreeGraphEditor;
				string json_string = ProcessTreeEditorHelper.ToJson(edit);
				string file_path = $"{ProcessTreeEditor.ProjectPath}/trees/{edit.Name}";
				FileAccess file = FileAccess.Open(file_path,FileAccess.ModeFlags.WriteRead);
				file.StoreString(json_string);
				file.Flush();
				file.Close();
			}
		}
	}

	
	public override void _Process(double delta)
	{
	}
}
